package com.its.common.net.core.util;

import com.its.common.net.core.dto.GenericNetDTO;
import io.netty.channel.Channel;
import java.net.SocketAddress;
import java.util.Objects;

/**
 * @Author xiaxp
 * @Date 9/15/22 16:52
 * @Description
 */
public class ChannelUtil {
    public static String extractRemoteAddr(final Channel channel) {
        if (null == channel) {
            return "";
        }
        SocketAddress remote = channel.remoteAddress();
        String addr1 = getAddrStringFromSocketAddress(remote);
        if (addr1 != null) {
            return addr1;
        }
        return "";
    }

    public static GenericNetDTO.Sender extractRemoteInfo(final Channel channel) {
        if (null == channel) {
            return null;
        }
        String addrAll = extractRemoteAddr(channel);
        return addrStr2Sender(addrAll);
    }

    public static String extractLocalAddr(final Channel channel) {
        if (null == channel) {
            return "";
        }
        SocketAddress local = channel.localAddress();
        String addr1 = getAddrStringFromSocketAddress(local);
        if (addr1 != null) {
            return addr1;
        }
        return "";
    }
    public static GenericNetDTO.Sender extractLocalInfo(final Channel channel) {
        if (null == channel) {
            return null;
        }
        String addrAll = extractLocalAddr(channel);
        return addrStr2Sender(addrAll);
    }

    private static String getAddrStringFromSocketAddress(SocketAddress remote) {
        final String addr = remote != null ? remote.toString() : "";
        if (addr.length() > 0) {
            int index = addr.lastIndexOf("/");
            if (index >= 0) {
                return addr.substring(index + 1);
            }
            return addr;
        }
        return null;
    }

    private static GenericNetDTO.Sender addrStr2Sender(String addrAll) {
        if (null == addrAll || Objects.equals("", addrAll.trim())) {
            return null;
        }
        addrAll.replaceAll("/", "");
        String[] arr = addrAll.split(":");
        GenericNetDTO.Sender sender = GenericNetDTO.Sender.builder()
                .address(arr[0])
                .port(Integer.parseInt(arr[1]))
                .build();
        return sender;
    }
}
